import {Injectable, Injector} from '@angular/core';
import {UrlTree} from '@angular/router';
import {BaseService} from './base/base.service';
import {ServicesModule} from './services.module';
import {getToken, isLogined, removeToken} from '../util/token.util';

@Injectable({
  providedIn: ServicesModule
})
export class LoginService extends BaseService {

  HOME = '/home';
  LOGIN = '/login';

  LOGOUT_API = this.uri + 'logout';
  TOKEN_API = this.uri + 'oauth/token';
  CHECK_TOKEN_API = this.uri + 'oauth/check_token';

  // 存储 URL，以便我们在登录后可以重定向
  redirectUrl: string;

  constructor(public injector: Injector) {
    super(injector);
  }

  login(data) {
    return this.httpServer.postForm<any>(this.TOKEN_API, data);
  }

  // 退出
  logout() {
    return this.httpServer.get(this.LOGOUT_API);
  }

  // 检测 token 在服务端是否还有效
  checkToken(): void {
    const oauth2ClientInfo = this.getOauth2ClientInfo();
    oauth2ClientInfo.token = getToken().split(' ')[1];
    this.httpServer.postForm(this.CHECK_TOKEN_API, oauth2ClientInfo).subscribe(next => {
      console.log('checkToken ok');
    }, error => {
      removeToken();
      this.routerRedirect();
    }, () => {
      console.log('checkToken ok');
    });
  }

  // 路由跳转
  routerRedirect(): void {
    let redirect: string | UrlTree = this.LOGIN;
    // 判断是否登陆
    if (isLogined()) {
      // 获取重定向 URL，如果未设置重定向，请使用默认值
      redirect = this.redirectUrl ? this.router.parseUrl(this.redirectUrl) : this.HOME;
      this.redirectUrl = null;
    }
    this.router.navigateByUrl(redirect);
  }

  getOauth2ClientInfo() {
    return {
      client_id: 'client',
      client_secret: 'yofcspis',
      grant_type: 'password',
      token: null,
      username: null,
      password: null
    };
  }
}
